import React, { useState, useEffect } from 'react';
import { Input, Space, Button, Modal, Table, Form, Typography, Popconfirm, InputNumber } from 'antd';
import { PriceBookStyle } from './style'
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';

import { setStorage, getStorage } from '@/utils/LocalStorage'

import { goodsprice } from '@/model/goodsModel.js'

const { Search } = Input;
const onSearch = value => console.log(value);

const layout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 10,
    },
};
const validateMessages = {
    required: '${label}不可为空'
};

const Index = () => {
    const [visible, setVisible] = useState(false);
    // 表格
    const originData = getStorage("goodsPrice") ? JSON.parse(getStorage("goodsPrice")) : [];

    const [goodsPrice , setGoodsPrice] = useState([])

    const [data, setData] = useState([]);
    async function getGoodsPrice(){
        let data = await goodsprice()
        data = data.data.data
        let list = [...data , ...originData]
        console.log(list);
        setGoodsPrice(list)
        setData(list)
    }
    const onFinish = (values) => {
        setVisible(false)
        originData.push({
            goodNum: values.data.goodNum,
            goodName: values.data.goodName,
            goodBrand: values.data.goodBrand,
            goodClassify: values.data.goodClassify,
            goodSpecs: values.data.goodSpecs,
            goodCompany: values.data.goodCompany,
            sellPrice: values.data.sellPrice,
            purchasePrice: values.data.purchasePrice,
            key: Date.now()
        })
        setStorage("goodsPrice", JSON.stringify(originData))
        // setData([...originData])
        setData(originData)
    }

    
    useEffect(() => {
        getGoodsPrice()
        setData(originData)
    }, []);

    const EditableCell = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `请输入${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    // 表格
    const [form] = Form.useForm();
    
    const [editingKey, setEditingKey] = useState('');

    const isEditing = (record) => record.key === editingKey;
    const edit = (record) => {
        form.setFieldsValue({
            name: '',
            age: '',
            ...record,
        });
        setEditingKey(record.key);
    };

    const cancel = () => {
        setEditingKey('');
    };

    const save = async (key) => {
        try {

            const row = await form.validateFields();

            const newData = [...data];
            const index = newData.findIndex((item) => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const columns = [
        {
            title: '商品编号',
            dataIndex: 'goodNum',
            editable: true,
        },
        {
            title: '商品名称',
            dataIndex: 'goodName',
            editable: true,
        },
        {
            title: '品牌',
            dataIndex: 'goodBrand',
            editable: true,
        },
        {
            title: '分类',
            dataIndex: 'goodClassify',
            editable: true,
        },
        {
            title: '规格',
            dataIndex: 'goodSpecs',
            editable: true,
        },
        {
            title: '单位',
            dataIndex: 'goodCompany',
            editable: true,
        },
        {
            title: '出售价格',
            dataIndex: 'sellPrice',
            editable: true,
        },
        {
            title: '进货价格',
            dataIndex: 'purchasePrice',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <a
                            href="javascript:void(0);"
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            确定
                        </a>
                        <Popconfirm title="确定取消？" onConfirm={cancel}>
                            <a>取消</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        修改
                    </Typography.Link>
                );
            },
        },
    ];
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });


    return (
        <>
            <PriceBookStyle>
                <div className="goodsTop">
                    <span>商品管理</span>
                /
                    <span>商品价格本</span>
                </div>
                <hr />
                <div className="searchAdd">
                    <Space direction="vertical" className="search">
                        <Search
                            placeholder="请输入属性组名称"
                            allowClear
                            enterButton="搜索"
                            size="middle"
                            onSearch={onSearch}
                        />
                    </Space>
                    <Button onClick={() => setVisible(true)} type="primary" icon={<CheckCircleOutlined />}>
                        添加
                    </Button>
                    <Modal
                        title="添加商品价格"
                        centered
                        visible={visible}
                        footer={null}
                        width={700}
                        onCancel={() => { setVisible(false) }}
                    >

                        <Form {...layout} onFinish={onFinish} validateMessages={validateMessages}>
                            <Form.Item
                                name={['data', 'goodNum']}
                                label="商品编号"
                                rules={[{ required: true }]}
                            >
                                <InputNumber />
                            </Form.Item>
                            <Form.Item
                                name={['data', 'goodName']}
                                label="商品名称"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                // goodBrand 商品品牌
                                name={['data', 'goodBrand']}
                                label="商品品牌"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name={['data', 'goodClassify']}
                                label="商品分类"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name={['data', 'goodSpecs']}
                                label="商品规格"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                // goodStock 商品库存
                                name={['data', 'goodCompany']}
                                label="商品单位"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                // goodStock 商品库存
                                name={['data', 'sellPrice']}
                                label="出售价格"
                                rules={[{ required: true }]}
                            >
                                <InputNumber />
                            </Form.Item>
                            <Form.Item
                                // goodStock 商品库存
                                name={['data', 'purchasePrice']}
                                label="进货价格"
                                rules={[{ required: true }]}
                            >
                                <InputNumber />
                            </Form.Item>
                            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 14 }}>
                                <Button type="primary" htmlType="submit" icon={<CheckCircleOutlined />}>添加</Button>
                            </Form.Item>
                            <Form.Item style={{ position: 'relative' }} wrapperCol={{ ...layout.wrapperCol, offset: 9 }}>
                                <Button
                                    style={{
                                        position: 'absolute',
                                        top: -55,
                                        left: -15,
                                        background: '#ddd',
                                        borderColor: "#ddd",
                                        color: "#000"
                                    }}
                                    type="primary"
                                    icon={<CloseCircleOutlined />}
                                    onClick={() => {
                                        setVisible(false)
                                    }}
                                >取消</Button>
                            </Form.Item>
                        </Form>

                    </Modal>
                </div>


                {/* 表格 */}
                <Form form={form} component={false}>
                    <Table
                        components={{ body: { cell: EditableCell } }}
                        bordered
                        dataSource={data}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        pagination={{
                            onChange: cancel,
                        }}
                    />
                </Form>

            </PriceBookStyle>
        </>
    );
}

export default Index;
